from django.shortcuts import render
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
from django.views import View
from meiduo_mall.utils.response_code import RETCODE
from random import randint
from celery_tasks.sms.tasks import send_sms_code
from . import constants
import logging
logger = logging.getLogger('django')


class ImaginCodeView(View):
    """图形验证码"""
    def get(self, request, uuid):
        name, text, image_bytes = captcha.generate_captcha()
        redis_con = get_redis_connection('verify_code')
        redis_con.setex(uuid, constants.IMAGE_CODE_EXPRIS_RESIS, text)
        return http.HttpResponse(image_bytes, content_type='image/png')


class SmsCodeView(View):
    """短信验证码"""
    # 前端请求地址 this.host + '/sms_codes/' + this.mobile + '/?image_code=' + this.image_code + '&uuid=' + this.uuid;
    def get(self,request, mobile):
        redis_conn = get_redis_connection('verify_code')
        # 防止客户端频繁发送短信
        send_flag = redis_conn.get('send_flag_%s'% mobile)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR, 'errmsg': '短信发送过于频繁'})
        #  接收数据
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验
        # 判断所传参数是否齐全，防止恶意请求
        if not all([image_code_client,uuid]):
            return http.HttpResponseForbidden('所传参数不全')
        image_code_server = redis_conn.get(uuid)
        # 从redis数据库取出验证码后直接删除使验证码在有效期内只能使用一次
        redis_conn.delete('uuid')
        # 判断验证码是否过期
        if image_code_server is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期'})
        # 注意判断之前要转码，转小写或大写比较提高用户体验
        if image_code_client.lower() != image_code_server.lower().decode():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码输入错误'})
        # 业务处理逻辑
        sms_code = '%06d'% randint(0,constants.SMS_CODE_MAX)

        logger.info(sms_code)
        # 把短信验证码保存到redis数据库中
        pl = redis_conn.pipeline()
        # redis_conn.setex('sms_code_%s'% mobile, constants.SMS_CODE_EXPRIS_REDIS, sms_code)
        pl.setex('sms_code_%s'% mobile, constants.SMS_CODE_EXPRIS_REDIS, sms_code)
        # 把手机号存到数据库中防止一台手机频繁发送短信
        # redis_conn.setex('send_flag_%s' % mobile, 60, mobile)
        pl.setex('send_flag_%s' % mobile, 60, mobile)
        pl.execute()
        send_sms_code.delay(mobile, sms_code)
        # 响应
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK'})